﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using InterfaceXAML.ExaPlanningService;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace InterfaceXAML
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class EditProfilPage : Page
    {
        public StorageFile ImageFile { get; set; }

        public EditProfilPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            var locations = await App.ExaPlanningServiceClient.GetAllLocationAsync();
            var activities = await App.ExaPlanningServiceClient.GetAllActivityAsync();
            var jobs = await App.ExaPlanningServiceClient.GetAllJobAsync();

            DataContext = new { Location = locations, Activity = activities, Job = jobs };

            Name.Document.SetText(Windows.UI.Text.TextSetOptions.Unhide, App.Utilisateur.Name);
            FirstName.Document.SetText(Windows.UI.Text.TextSetOptions.Unhide, App.Utilisateur.FirstName);
            Email.Document.SetText(Windows.UI.Text.TextSetOptions.Unhide, App.Utilisateur.Email);
            Phone.Document.SetText(Windows.UI.Text.TextSetOptions.Unhide, App.Utilisateur.MobilePhone);
            Image.Source = App.Utilisateur.ImageInfo;
            Location.SelectedIndex = App.Utilisateur.LocationID - 1;
            Job.SelectedIndex = App.Utilisateur.JobID - 1;
            Activity.SelectedIndex = App.Utilisateur.ActivityID - 1;
        }

        private void BackButtonClick(object sender, RoutedEventArgs e)
        {
            if (Frame.CanGoBack)
                Frame.GoBack();
        }

        private async void EditionClick(object sender, RoutedEventArgs args)
        {
            var password = Password.Password;
            var passwordConfirm = PasswordConfirm.Password;
            var name = String.Empty;
            var firstName = String.Empty;
            var mail = String.Empty;
            var phone = String.Empty;

            var indexLocation = Location.SelectedIndex;
            var indexActivity = Activity.SelectedIndex;
            var indexJob = Job.SelectedIndex;
            int location = 0;
            int activity = 0;
            int job = 0;
            byte[] buffe = null;

            Name.Document.GetText(Windows.UI.Text.TextGetOptions.NoHidden, out name);
            FirstName.Document.GetText(Windows.UI.Text.TextGetOptions.NoHidden, out firstName);
            Email.Document.GetText(Windows.UI.Text.TextGetOptions.NoHidden, out mail);
            Phone.Document.GetText(Windows.UI.Text.TextGetOptions.NoHidden, out phone);

            Password.BorderBrush = Application.Current.Resources["CorrectField"] as SolidColorBrush;
            PasswordConfirm.BorderBrush = Application.Current.Resources["CorrectField"] as SolidColorBrush;
            Name.BorderBrush = Application.Current.Resources["CorrectField"] as SolidColorBrush;
            FirstName.BorderBrush = Application.Current.Resources["CorrectField"] as SolidColorBrush;
            Email.BorderBrush = Application.Current.Resources["CorrectField"] as SolidColorBrush;
            Phone.BorderBrush = Application.Current.Resources["CorrectField"] as SolidColorBrush;
            Location.DisplayNormal();
            Activity.DisplayNormal();
            Job.DisplayNormal();

            if (String.IsNullOrWhiteSpace(password))
                Password.BorderBrush = Application.Current.Resources["ErrorField"] as SolidColorBrush;

            if (String.IsNullOrWhiteSpace(passwordConfirm) || !password.Equals(passwordConfirm))
                PasswordConfirm.BorderBrush = Application.Current.Resources["ErrorField"] as SolidColorBrush;

            if (String.IsNullOrWhiteSpace(name))
                Name.BorderBrush = Application.Current.Resources["ErrorField"] as SolidColorBrush;

            if (String.IsNullOrWhiteSpace(firstName))
                FirstName.BorderBrush = Application.Current.Resources["ErrorField"] as SolidColorBrush;

            if (String.IsNullOrWhiteSpace(mail))
                Email.BorderBrush = Application.Current.Resources["ErrorField"] as SolidColorBrush;

            if (String.IsNullOrWhiteSpace(phone))
                Phone.BorderBrush = Application.Current.Resources["ErrorField"] as SolidColorBrush;

            if (indexLocation == -1)
                Location.DisplayError();
            location = (Location.SelectItem as LocationViewModel).ID;

            if (indexActivity == -1)
                Activity.DisplayError();
            activity = (Activity.SelectItem as ActivityViewModel).ID;

            if (indexJob == -1)
                Job.DisplayError();
            job = (Job.SelectItem as JobViewModel).ID;

            if (ImageFile != null)
            {
                var stream = await ImageFile.OpenReadAsync();
                var reader = new DataReader(stream.GetInputStreamAt(0));
                buffe = new byte[(uint)stream.Size];
                await reader.LoadAsync((uint)stream.Size);
                reader.ReadBytes(buffe);
            }

            // Appel au WebService
            try
            {
                await App.ExaPlanningServiceClient.EditProfileAsync(password, name, firstName, phone, mail, buffe); //job, location, activity,
            }
            catch (Exception e)
            {

            }
        }

        private async void FileChooserClick(object sender, RoutedEventArgs e)
        {
            var filePicker = new FileOpenPicker();
            filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            filePicker.FileTypeFilter.Add(".jpg");
            filePicker.FileTypeFilter.Add(".png");
            var file = await filePicker.PickSingleFileAsync();

            // Au cas où l'utilisateur clique sur le bouton Annuler
            if (file == null)
                return;

            var bmp = new BitmapImage();
            var fileStorage = await file.OpenReadAsync();

            bmp.SetSource(fileStorage);
            Image.SourceWithoutCaching = bmp;
            ImageFile = file;
        }

        private void ClearFileChooserClick(object sender, RoutedEventArgs e)
        {
            Image.SourceWithoutCaching = null;
            ImageFile = null;
        }

    }
}
